let startDateIns;
let endDateIns;
let tableIns;
let tree;
layui.use(['table', 'form','layer', 'laydate', 'tree', 'util'], function () {
    let table = layui.table , form = layui.form;
    tree = layui.tree;
    let laydate = layui.laydate;
    let height = document.documentElement.clientHeight - 60;
    
    findMoney();

    tableIns = table.render({
        elem: '#grantTable'
        , url: '/platform/grant/list/page'
        , method: 'POST'
        //请求前参数处理
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'rows' //每页数据量的参数名，默认：limit
        }
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'records' //规定数据总数的字段名称，默认：count
            , dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            console.log(data);
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "records": data.records, //解析数据长度
                "rows": data.rows //解析数据列表
            };
        }
        , title: '发放记录'
        , cols: [[
            {field: 'serviceId', title: 'ID', hide: true}
            , {field: 'orderId', title: '订单号'}
            , {field: 'applyTime',title: '申请时间'}
            , {field: 'endTime',title: '操作时间',templet:function (d) {
                    var _s = (d.approveStatus == "0") ? "" : d.endTime;
                    return _s;
                }}
            , {field: 'sellName', title: '商户名称'}
            , {field: 'serviceName', title: '服务商名称'}
            , {field: 'realAmount', title: '应发金额', templet:function (d) {
                    return '￥' + formatMoney(d.realAmount) + '元';
                }}
            , {field: 'realAmount', title: '实发金额', templet:function (d) {
                    var _amountStr = (d.realAmount - ((d.failedAmount==null || d.failedAmount==undefined || d.failedAmount=='')?0:d.failedAmount));
                    return (d.orderType != "1") ? "" :'￥' + formatMoney(_amountStr) + '元';
                }}
            /*  , {field: 'serviceAmount', title: '服务费', templet:function (d) {
                      return '￥' + d.serviceAmount + '元';
                  }}*/
            //  , {field: 'bizContent', title: '业务处理情况'}
            , {title: '订单状态' ,toolbar: '#staBar'}
            /*, { title: '发放' ,toolbar: '#downLoadBar'}*/
            , {field: 'provideList', title: '操作',templet:function (d) {
                    var html = '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="downLoad">下载拆分清单</a><br/>' +
                        '<a href="javascript:;" class="layui-btn layui-btn-xs" onclick=window.open("'+d.provideList+'")>下载发放名单</a><br/>' 
                        
                        if(d.reportFile != null && d.reportFile != '' && d.reportFile != 'undefined'){
                        html += '<a href="javascript:;" class="layui-btn layui-btn-xs" lay-event="downFile" >下载验收报告</a>';
                        }
                    return html;
                }}
        ]]
        ,done:function(res){
        	console.log(res);
        }
        ,defaultToolbar: ['', '', '']
        , page: true
        , height: height
        , cellMinWidth: 80
    });

    table.on('tool(display)',function (obj) {
        var _data = obj.data;
        /*
        if(obj.event === 'grantSet'){

            console.log("id===grantSet=="+_data+"obj.event="+obj.event);

            console.log("_data.orderId=="+_data.orderId);

            layer.open({
                type: 2,
                title: '发放设置',
                shade: 0.2,
                maxmin:true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: '/platform/grantdetail/list',
                success: function(layero, index){
                    var frameId = $(layero).find('iframe').attr("id");
                    //找到子页面的document对象
                    var document = window.frames[frameId].document;
                    //根据id找到子页面中相应的元素并赋值
                    $(document).find("input[name='orderId']").val(_data.orderId);

                },
                end: function () {
                    location.reload();
                }
            });
        }

         */

        if(obj.event === 'downLoad'){
            window.open("/platform/grant/export?platformGrantId="+_data.orderId);
        }
        
      //下载验收报告
        else if (obj.event === 'downFile') {
            window.open("/platform/grant/downFile?fileName="+_data.reportFile);
        }

        if(obj.event === 'detailsInfo'){
            /*
            $.get('/platform/grant/list/detail?platformGrantId='+_data.orderId,
                '', function (res) {
                    //$("#queryBySellerNameBtn").click();
                    layer.open({
                        title:'发放明细',
                        type: 1
                        ,offset: 'auto' //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
                        ,closeBtn: false
                        ,id: 'layerDemoauto1' //防止重复弹出
                        ,area: ['90%', '600px']
                        ,btn: ['查询所有明细', '关闭']
                        ,btnAlign: 'c' //按钮居中
                        ,shade: 0.2 //不显示遮罩
                        ,shadeClose: true //开启遮罩关闭
                        ,content: '<div>' +
                            '<table id="templateTable1" lay-filter="templateTable1"></table>' +
                            '</div>'
                        ,success: function (index, layero) {
                            var table = layui.table;
                            console.info("table:" + table);
                            console.info("res:" + res);
                            table.render({
                                elem: '#templateTable1'
                                , data: res //result格式为[{},{}],此处用的是固定数据,也可以用url来请求后台获取数据,如果使用url要根据layui规定的格式返回才可以渲染上,例：{"code": 0,"msg": "","count": 1000,"data": [{}, {}]} 或者使用parseData进行转化也可以
                                , cols: [
                                    [
                                        {field: 'id',title: '明细单号', hide: true},
                                        {field: 'cardCode',title: '收款人身份证号', hide: true},
                                        {field: 'payeeAccount',title: '收款人账号', hide: true},
                                        {field: 'payeeName', title: '收款人姓名'},
                                        {field: 'payeeMobile', title: '收款人手机'},
                                        {field: 'payAmount', title: '金额'},
                                        {field: 'payeeAccountBankName', title: '开户行'},
                                        {field: 'paymentStatus', title: '状态码'},
                                        {field: 'paymentMsg', title: '状态说明'},
                                        {field: 'orderType', title: '操作', align: 'center',
                                            templet: function(d){
                                                if(d.orderType == "P"){
                                                    return "<a class='layui-btn layui-btn-xs' data-id='d.orderId' lay-event='detailsInfo'>发起查询</a>";
                                                }
                                            }
                                        }
                                    ]
                                ]
                                , height : 'auto'
                                , page: false //使用分页
                            });


                        },btn1: function(){


                        },btn2: function(){

                        }

                    });
                });
                */
            layer.open({
                title:'发放明细支付结果'
                ,type: 2
                ,offset: 'auto' //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
                ,closeBtn: false
                ,id: 'templateTable' //防止重复弹出
                ,area: ['90%', '600px']
                ,btn: ['刷新支付状态', '关闭']
                ,btnAlign: 'c' //按钮居中
                ,shade: 0.2 //不显示遮罩
                ,shadeClose: true //开启遮罩关闭
                ,content: '/platform/grant/list/listInfo?' + _data.orderId
                ,success: function(layero, index){

                },btn1: function(){
                	 var frameId=document.getElementById('templateTable').getElementsByTagName("iframe")[0].id;//获取iframe页面的id！
                     $('#'+frameId)[0].contentWindow.location.reload();//子页面刷新！
                     layer.msg("操作完成！");

                },btn2: function(){

                }
            });
        }
    });



    form.on('select(editSta)',function (obj) {
        var _val = obj.value,
            _status = _val.split('|')[0],
            _id = _val.split('|')[1];

        var str = "";

        if(_status == 0){
            //如果选择审核中不做任何操作
            return;
        }

        if(_status == 1){
            str = "确认要通过该审核？";
        }else{
            str = "确认要拒绝该审核？"
        }

        layer.confirm(str,{ btn : ["确定", "取消"], btn1 : function (index) {
                $.post("/platform/grant/update", {orderId:_id,approveStatus:_status,orderType:"0"}, function (res) {
                    var data = JSON.parse(res);
                    console.log("flag=="+res);
                    console.log("data=="+data);
                    if(data.flag){
                        layer.msg("审核成功", {icon: 1, time: 2000}, function(){
                            console.log("table"+table);
                            //执行重载
                            tableIns.reload('testReload', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                                , done: function (res, curr, count) {
                                    //完成后重置where，解决下一次请求携带旧数据
                                    this.where = {};
                                }
                            }, 'data');
                        });
                    } else {
                        layer.msg("审核失败!", {icon: 5});
                    }
                });
            }, btn2 : function(){
                //取消操作
                $("select[name='interest']").children("option").removeProp("selected");
                $("select[name='interest']").children("option").eq(0).prop("selected");
                layer.msg("操作已取消!", {icon: 2});
            }
        });
    });


    form.on('submit(menu-query)', function (data) {

        // 搜索条件
        var sellerName=data.field.sellerName;
        var serviceName=data.field.serviceName;
        var startDate=data.field.startDate;
        var endDate=data.field.endDate;
        var orderId=data.field.orderId;
        // var tel=$("#tel").val();
        table.reload('grantTable', {
            url:'/platform/grant/queryApply'
            , where: {
                'sellerName':sellerName,
                'serviceName':serviceName,
                'startDate':startDate,
                'endDate':endDate,
                'orderId':orderId,
            }
            , page: {
                curr: 1
            }
        });
        
        findMoney();
        return false;

    });

    //日期选择器
    startDateIns = laydate.render({
        elem: '#queryByStartDate',
        format: "yyyy-MM-dd",
        trigger: 'click'
    });


    //日期选择器
    endDateIns = laydate.render({
        elem: '#queryByEndDate',
        format: "yyyy-MM-dd",
        trigger: 'click'
    });
    
    form.on('submit(exportAll)', function(){
    	location.href= '/platform/grant/exportGrant?sellerName='+ $("#sellerName").val() + "&serviceName=" + $("#serviceName").val() + "&startDate=" + $("#queryByStartDate").val() + "&endDate=" + $("#queryByEndDate").val()
		+ "&orderId=" + $("#orderId").val();
		  //alert("导出");
	  });

});


function formatMoney(str) {
    if (!str) str = '0.00';
    let ret = Math.round(parseFloat(str) * 100) / 100;
    let decimal = ret.toString().split('.');
    if (decimal.length === 1) {
        return ret.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            + '.00';
    };
    if (decimal.length > 1) {
        decimal[0] = decimal[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        if (decimal[1].length < 2) {
            decimal[1] += '0';
            return decimal.join(".");
        }
        return decimal.join(".");
    };
    return ret;
}

function findMoney(){
    $.post('/platform/grant/findMoney?sellerName='+ $("#sellerName").val() + "&serviceName=" + $("#serviceName").val() + "&startDate=" + $("#queryByStartDate").val() + "&endDate=" + $("#queryByEndDate").val()
    		+ "&orderId=" + $("#orderId").val(), {}, function (data) {
    			
                $("#sum_money1").html("审核中总金额："+formatMoney(data.data[0].examineing));
                $("#sum_money2").html("已发放总金额："+formatMoney(data.data[0].examineed));
                $("#sum_money3").html("已取消总金额："+formatMoney(data.data[0].examineno));
    })
}


